package com.boardgame.users.controller;


import com.boardgame.common.entity.ResponseInfo;
import com.boardgame.users.dto.PlayerInfoDto;
import com.boardgame.users.entity.PlayerInfo;
import com.boardgame.users.repository.PlayerInfoRepository;
import com.boardgame.users.service.PlayerInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * Created by pdybka on 27.05.16.
 */

@RestController
@RequestMapping("/players")
public class PlayerInfoController {

    @Autowired
    PlayerInfoService playerInfoService;

    @Autowired
    private PlayerInfoRepository playerInfoRepository;

    /**
     * 注册
     * @param newPlayerDTO
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ResponseInfo<PlayerInfo> createAccount(@RequestBody PlayerInfoDto newPlayerDTO) {
        //判断用户名
        if (playerInfoRepository.findOneByUserName(newPlayerDTO.getUserName())!=null){
            return ResponseInfo.Failed("用户已经存在");
        }
        //判断邮箱
        else if (playerInfoRepository.findOneByEmail(newPlayerDTO.getEmail())!=null){
            return ResponseInfo.Failed("邮箱已经存在");
        }
        PlayerInfo newPlayer = playerInfoService.createNewPlayer(newPlayerDTO);
        return ResponseInfo.Success(newPlayer);
    }

    /**
     * 全部用户
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseInfo getPlayers() {
        List list = playerInfoService.listPlayers();
        return ResponseInfo.Success(list);
    }

    @RequestMapping(value = "/logged", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseInfo<PlayerInfo> getLoggedPlayer() {
        return  ResponseInfo.Success(playerInfoService.getLoggedUser());
    }

    @Autowired
    WebApplicationContext applicationContext;
    @GetMapping("/getAllUrl")
    @ResponseBody
    public List<String> getAllUrl(){
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        List<String> urlList = new ArrayList<>();
        for (RequestMappingInfo info : map.keySet()){
            //获取url的Set集合，一个方法可能对应多个url
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            for (String url : patterns){
                urlList.add(url);
            }
        }
        return urlList;
    }

}


